<?php
namespace App\Financeiro\Controller;

use Foxforms\Widget\Field\Radio;

use Foxforms\Widget\Field\Select;

use Foxforms\Widget\Field\Input;

use Foxforms\Widget\Form;

class contaController extends \Foxframe\Controller
{
	public function viewListar($params = array())
	{
		$lista	= $this->em->getRepository('\Entities\Financeiro\Conta')->findAll();
		$this->view->assign('lista', $lista);
	}

	public function viewSalvarConta($params = array())
	{
		if (isset($params['id']) && !empty($params['id']))
			$conta	= $this->em->find('\Entities\Financeiro\Conta', $params['id']);
		else
			$conta	= new \Entities\Financeiro\Conta();

		$form	= new Form();
		$form->addValues($conta, 'conta');
		$form->addElement(Input::create('application')->setType('hidden')->setValue('financeiro'));
		$form->addElement(Input::create('controller')->setType('hidden')->setValue('conta'));
		$form->addElement(Input::create('method')->setType('hidden')->setValue('saveSalvarConta'));
		$form->addElement(Input::create('conta[version]')->setType('hidden'));
		$form->addElement(Input::create('conta[id_conta]')->setType('hidden'));
		$form->addElement(Input::create('conta[ds_nome]')->setType('text')->setLabel('Nome')->validate());
		$form->addElement(
				Select::create('conta[banco]')
				->setOption($this->em->getRepository('\Entities\Corp\Pessoa')->listBancoCombo())
				->setLabel('Banco')
				->setPlaceHolder('--Selecione--')
			);
		$form->addElement(
				Radio::create('conta[tp_conta]')
				->setOption(array('B' => 'Banco', 'C' => 'Caixa', 'I' => 'Investimento'))
				->setLabel('Tipo')
				->validate()
			);
		$form->addElement(Input::create('salvar')->setType('submit')->setValue('Salvar')->addClass(array('btn','btn-primary')));
		$this->view->assign('form', $form);
		return $this->returnAjax();
	}

	public function saveSalvarConta($params = array())
	{
		try
		{
			$entity	= new \Foxframe\Service();
			$entity->save($params['conta'], '\Entities\Financeiro\Conta');
			$this->em->flush();

			$this->setFlash('Success', 'Sucesso', "Conta salva com sucesso");
		}
		catch (\Exception $e)
		{
			$this->setFlash('Error', 'Erro', $e->getMessage());
		}
		$this->redirect($this->uri->getOrigem());
	}
}